<?php

namespace app\admin\controller\user;

use app\admin\model\video\Videovip;
use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\model\Userchildren;
use fast\Random;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 会员管理
 *
 * @icon fa fa-circle-o
 */
class Usertwo extends Backend
{

    /**
     * Usertwo模型对象
     * @var \app\admin\model\user\Usertwo
     */
    protected $model = null;
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\user\Usertwo;
        $this->view->assign("payList", $this->model->getPayList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','wallet','username','nickname','mobile','avatar','money','video_end_time','createtime','parent_user_id','goods_parent_user_id','invite_code','go_money','wallet_end_time']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $auth                     = new Auth();
            $extend['username']       = $params['username'];
            $extend['nickname']       = $params['nickname'];
            $extend['parent_user_id'] = $params['parent_user_id'];
            $result =  $auth->register($params['username'], $params['password'], $params['email'], $params['mobile'], $extend);
            if(!$result){
                $this->error($auth->getError());
            }
            if($params['money'] != 0){
                controller('addons\wanlshop\library\WanlPay\WanlPay')->money(+$params['money'], $auth->getUserinfo()['id'], '管理员操作', 'admin', $this->auth->id);
            }
            if($params['wallet'] != 0){
                controller('addons\wanlshop\library\WanlPay\WanlPay')->wallet(+$params['wallet'], $auth->getUserinfo()['id'], '管理员操作', 'admin', $this->auth->id);

            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }


    /**
     * 修改观影时长
     * @param null $ids
     * @return string|void
     * @throws DbException
     * @throws \think\Exception
     */
    public function videoedit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            if($row->video_end_time){
                $row->video_end_time = date('Y-m-d H:i:s',$row->video_end_time);
            }

            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if($params['video_end_id']){
                $day = Videovip::where(['id'=>$params['video_end_id']])->value('vip_time');
                if($row['video_end_time'] > 0){
                    $params['video_end_time'] = $row['video_end_time']+$day*86400;
                }else{
                    $params['video_end_time'] = time()+$day*86400;
                }
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            if($row->video_end_time){
                $row->video_end_time = date('Y-m-d H:i:s',$row->video_end_time);
            }

            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
           $password = (new \app\common\library\Auth)->getEncryptPassword($params['password'],$row['salt']);
            if($password != $row['password']){
                $params['password']  = $password;
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 充值
     *
     * @return string
     * @throws \think\Exception
     */
    public function chongzhi($id)
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if (!in_array($params['type'], ['money', 'wallet','go_money'])) {
            $this->error('参数错误');
        }
        $row = $this->model->where(['id'=>$id])->find();
        if(!$row){
            $this->error('会员不存在');
        }
        if($params['amount'] > 0){
            +$money = $params['amount'];
        }else{
            -$money = $params['amount'];
        }
        if($params['type'] == 'money'){
            controller('addons\wanlshop\library\WanlPay\WanlPay')->money($money, $row['id'], $params['memo'], 'admin', $this->auth->id);
        }else if($params['type'] == 'wallet'){
            controller('addons\wanlshop\library\WanlPay\WanlPay')->wallet($money,$row['id'], $params['memo'], 'admin', $this->auth->id);
        }else{
            controller('addons\wanlshop\library\WanlPay\WanlPay')->goMoney($money,$row['id'], $params['memo'], 'admin', $this->auth->id);
        }
        $this->success();
    }
}
